<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>体重趋势图表</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            warning: '#FF9F43',
            danger: '#FF5252',
            dark: '#333647',
            light: '#F9FAFB'
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .chart-container {
        position: relative;
        height: 300px;
        width: 100%;
      }
      .stats-card {
        @apply bg-white rounded-xl shadow-md p-4 transition-all duration-300 hover:shadow-lg;
      }
      .btn-toggle {
        @apply px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2;
      }
      .btn-toggle.active {
        @apply bg-primary text-white focus:ring-primary;
      }
      .btn-toggle:not(.active) {
        @apply bg-gray-100 text-gray-700 hover:bg-gray-200 focus:ring-gray-400;
      }
    }
  </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen">
  <div th:replace="~{layout/base :: nav}"></div>

  <main class="container my-4">
    <div class="max-w-6xl mx-auto px-4 py-8">
      <!-- 标题区域 -->
      <div class="mb-8 text-center">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-2">体重趋势分析</h1>
        <p class="text-gray-500 text-lg">追踪你的健康旅程，掌握体重变化</p>
      </div>
      
      <!-- 控制面板 -->
      <div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-4">
        <div class="flex space-x-2 bg-white p-1 rounded-lg shadow-sm">
          <button id="btn-week" class="btn-toggle active">周视图</button>
          <button id="btn-month" class="btn-toggle">月视图</button>
          <button id="btn-year" class="btn-toggle">年视图</button>
        </div>
        
        <div class="flex items-center gap-4">
          <div class="relative">
            <input type="date" id="start-date" class="rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 p-2 w-44">
          </div>
          <button id="refresh-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-md transition-all duration-200 flex items-center gap-2 shadow-sm">
            <i class="fa fa-refresh"></i>
            <span>刷新数据</span>
          </button>
        </div>
      </div>
      
      <!-- 图表区域 -->
      <div class="bg-white rounded-xl shadow-md p-6 mb-8 transform transition-all duration-300 hover:shadow-lg">
        <div class="chart-container">
          <canvas id="weightChart"></canvas>
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="stats-card border-l-4 border-primary">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-500 text-sm">当前体重</p>
              <h3 id="current-weight" class="text-2xl font-bold">68.5<span class="text-sm font-normal ml-1">kg</span></h3>
            </div>
            <div class="bg-primary/10 p-3 rounded-full">
              <i class="fa fa-balance-scale text-primary text-xl"></i>
            </div>
          </div>
          <div class="mt-3">
            <div class="flex items-center text-sm">
              <i class="fa fa-arrow-down text-secondary mr-1"></i>
              <span class="text-secondary font-medium">1.2kg</span>
              <span class="text-gray-500 ml-1">较上周</span>
            </div>
          </div>
        </div>
        
        <div class="stats-card border-l-4 border-secondary">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-500 text-sm">目标体重</p>
              <h3 id="target-weight" class="text-2xl font-bold">65<span class="text-sm font-normal ml-1">kg</span></h3>
            </div>
            <div class="bg-secondary/10 p-3 rounded-full">
              <i class="fa fa-bullseye text-secondary text-xl"></i>
            </div>
          </div>
          <div class="mt-3">
            <div class="flex items-center text-sm">
              <i class="fa fa-trophy text-warning mr-1"></i>
              <span class="text-warning font-medium">3.5kg</span>
              <span class="text-gray-500 ml-1">剩余目标</span>
            </div>
          </div>
        </div>
        
        <div class="stats-card border-l-4 border-warning">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-500 text-sm">本周最低点</p>
              <h3 id="min-weight" class="text-2xl font-bold">68.2<span class="text-sm font-normal ml-1">kg</span></h3>
            </div>
            <div class="bg-warning/10 p-3 rounded-full">
              <i class="fa fa-arrow-circle-down text-warning text-xl"></i>
            </div>
          </div>
          <div class="mt-3">
            <div class="flex items-center text-sm">
              <span class="text-gray-600">日期: </span>
              <span class="font-medium">2025-06-07</span>
            </div>
          </div>
        </div>
        
        <div class="stats-card border-l-4 border-danger">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-500 text-sm">本周最高点</p>
              <h3 id="max-weight" class="text-2xl font-bold">70.1<span class="text-sm font-normal ml-1">kg</span></h3>
            </div>
            <div class="bg-danger/10 p-3 rounded-full">
              <i class="fa fa-arrow-circle-up text-danger text-xl"></i>
            </div>
          </div>
          <div class="mt-3">
            <div class="flex items-center text-sm">
              <span class="text-gray-600">日期: </span>
              <span class="font-medium">2025-06-03</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 数据表格 -->
      <div class="bg-white rounded-xl shadow-md p-6 mb-8 transform transition-all duration-300 hover:shadow-lg overflow-hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold">详细数据</h2>
          <div class="flex items-center gap-2">
            <span class="text-sm text-gray-500">显示:</span>
            <select id="table-limit" class="text-sm border-gray-300 rounded-md p-1 focus:border-primary focus:ring focus:ring-primary/20">
              <option value="7">7 天</option>
              <option value="14">14 天</option>
              <option value="30">30 天</option>
              <option value="90">90 天</option>
            </select>
          </div>
        </div>
        
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">体重 (kg)</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">变化</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">趋势</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody id="weight-table-body" class="bg-white divide-y divide-gray-200">
              <!-- 表格内容将通过JavaScript动态生成 -->
            </tbody>
          </table>
        </div>
        
        <div id="table-pagination" class="mt-4 flex justify-between items-center">
          <div class="text-sm text-gray-500">
            显示 <span id="showing-start">1</span> 到 <span id="showing-end">7</span> 条，共 <span id="total-entries">7</span> 条
          </div>
          <div class="flex space-x-1">
            <button id="prev-page" class="px-3 py-1 rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed">
              <i class="fa fa-chevron-left"></i>
            </button>
            <button id="next-page" class="px-3 py-1 rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed">
              <i class="fa fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 添加体重模态框 -->
      <div id="add-weight-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold">添加体重记录</h3>
            <button id="close-modal" class="text-gray-500 hover:text-gray-700">
              <i class="fa fa-times text-xl"></i>
            </button>
          </div>
          
          <form id="add-weight-form">
            <div class="mb-4">
              <label for="weight-value" class="block text-sm font-medium text-gray-700 mb-1">体重 (kg)</label>
              <input type="number" id="weight-value" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 p-2" step="0.1" required>
            </div>
            
            <div class="mb-4">
              <label for="weight-date" class="block text-sm font-medium text-gray-700 mb-1">日期</label>
              <input type="date" id="weight-date" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 p-2" required>
            </div>
            
            <div class="flex justify-end space-x-3 mt-6">
              <button type="button" id="cancel-add" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-all duration-200">取消</button>
              <button type="submit" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-md transition-all duration-200">添加记录</button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 页脚 -->
      <footer class="text-center text-gray-500 text-sm py-4">
        <p>© 2025 体重追踪应用 | 健康生活从记录开始</p>
      </footer>
    </div>

    <script>
      // 示例数据
      const sampleData = [
        { date: '2025-06-03', weight: 70.1 },
        { date: '2025-06-04', weight: 69.8 },
        { date: '2025-06-05', weight: 69.5 },
        { date: '2025-06-06', weight: 69.3 },
        { date: '2025-06-07', weight: 68.2 },
        { date: '2025-06-08', weight: 68.7 },
        { date: '2025-06-09', weight: 68.5 }
      ];
      
      // 生成更多示例数据（用于月视图和年视图）
      function generateSampleData(days) {
        const data = [];
        const today = new Date();
        
        for (let i = days - 1; i >= 0; i--) {
          const date = new Date(today);
          date.setDate(today.getDate() - i);
          const dateStr = date.toISOString().split('T')[0];
          
          // 生成随机体重（在68-72kg之间波动）
          const baseWeight = 68;
          const fluctuation = Math.random() * 4;
          const weight = Math.round((baseWeight + fluctuation) * 10) / 10;
          
          data.push({ date: dateStr, weight });
        }
        
        return data;
      }
      
      // 全局变量
      let currentData = [...sampleData];
      let currentView = 'week';
      let currentPage = 1;
      let recordsPerPage = 7;
      let chart = null;
      let targetWeight = 65;
      
      // DOM 加载完成后初始化
      document.addEventListener('DOMContentLoaded', () => {
        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('start-date').value = today;
        document.getElementById('weight-date').value = today;
        
        // 初始化图表
        initChart();
        
        // 初始化表格
        updateTable();
        
        // 设置事件监听器
        document.getElementById('btn-week').addEventListener('click', () => switchView('week'));
        document.getElementById('btn-month').addEventListener('click', () => switchView('month'));
        document.getElementById('btn-year').addEventListener('click', () => switchView('year'));
        document.getElementById('refresh-btn').addEventListener('click', refreshData);
        document.getElementById('table-limit').addEventListener('change', updateRecordsPerPage);
        document.getElementById('prev-page').addEventListener('click', prevPage);
        document.getElementById('next-page').addEventListener('click', nextPage);
        document.getElementById('add-weight-form').addEventListener('submit', addWeightRecord);
        document.getElementById('close-modal').addEventListener('click', closeModal);
        document.getElementById('cancel-add').addEventListener('click', closeModal);
        
        // 模态框动画
        const modal = document.getElementById('add-weight-modal');
        const modalContent = document.getElementById('modal-content');
        
        modal.addEventListener('click', (e) => {
          if (e.target === modal) {
            closeModal();
          }
        });
      });
      
      // 初始化图表
      function initChart() {
        const ctx = document.getElementById('weightChart').getContext('2d');
        
        // 销毁已存在的图表
        if (chart) {
          chart.destroy();
        }
        
        // 准备图表数据
        const labels = currentData.map(item => formatDate(item.date));
        const weights = currentData.map(item => item.weight);
        
        // 查找最小值和最大值
        const minWeight = Math.min(...weights);
        const maxWeight = Math.max(...weights);
        const minWeightData = currentData.find(item => item.weight === minWeight);
        const maxWeightData = currentData.find(item => item.weight === maxWeight);
        
        // 更新统计卡片
        document.getElementById('current-weight').textContent = weights[weights.length - 1];
        document.getElementById('min-weight').textContent = minWeight;
        document.getElementById('max-weight').textContent = maxWeight;
        
        // 计算趋势线数据
        const trendData = calculateTrend(weights);
        
        // 创建图表
        chart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: labels,
            datasets: [
              {
                label: '体重 (kg)',
                data: weights,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22, 93, 255, 0.1)',
                borderWidth: 2,
                pointBackgroundColor: '#165DFF',
                pointRadius: 4,
                pointHoverRadius: 6,
                tension: 0.3,
                fill: true
              },
              {
                label: '趋势线',
                data: trendData,
                borderColor: '#36D399',
                borderWidth: 2,
                borderDash: [5, 5],
                pointRadius: 0,
                fill: false,
                tension: 0.3
              },
              {
                label: '目标体重',
                data: Array(weights.length).fill(targetWeight),
                borderColor: '#FF9F43',
                borderWidth: 2,
                borderDash: [3, 3],
                pointRadius: 0,
                fill: false
              }
            ]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
              mode: 'index',
              intersect: false,
            },
            plugins: {
              legend: {
                position: 'top',
                labels: {
                  usePointStyle: true,
                  boxWidth: 6
                }
              },
              tooltip: {
                backgroundColor: 'rgba(0, 0, 0, 0.7)',
                padding: 10,
                cornerRadius: 8,
                callbacks: {
                  label: function(context) {
                    let label = context.dataset.label || '';
                    if (label) {
                      label += ': ';
                    }
                    if (context.parsed.y !== null) {
                      label += context.parsed.y.toFixed(1) + ' kg';
                    }
                    return label;
                  }
                }
              },
              annotation: {
                annotations: {
                  minWeight: {
                    type: 'point',
                    xValue: labels.indexOf(formatDate(minWeightData.date)),
                    yValue: minWeight,
                    backgroundColor: '#36D399',
                    borderColor: '#fff',
                    borderWidth: 2,
                    radius: 6,
                    label: {
                      content: '本周最低',
                      enabled: true,
                      position: 'top',
                      backgroundColor: '#36D399',
                      color: 'white',
                      font: {
                        size: 11
                      },
                      padding: {
                        top: 4,
                        bottom: 4,
                        left: 6,
                        right: 6
                      },
                      borderRadius: 4
                    }
                  },
                  maxWeight: {
                    type: 'point',
                    xValue: labels.indexOf(formatDate(maxWeightData.date)),
                    yValue: maxWeight,
                    backgroundColor: '#FF5252',
                    borderColor: '#fff',
                    borderWidth: 2,
                    radius: 6,
                    label: {
                      content: '本周最高',
                      enabled: true,
                      position: 'top',
                      backgroundColor: '#FF5252',
                      color: 'white',
                      font: {
                        size: 11
                      },
                      padding: {
                        top: 4,
                        bottom: 4,
                        left: 6,
                        right: 6
                      },
                      borderRadius: 4
                    }
                  }
                }
              }
            },
            scales: {
              x: {
                grid: {
                  display: false
                },
                ticks: {
                  maxRotation: 0,
                  font: {
                    size: 11
                  }
                }
              },
              y: {
                beginAtZero: false,
                min: Math.floor(Math.min(...weights) - 2),
                max: Math.ceil(Math.max(...weights) + 2),
                grid: {
                  color: 'rgba(0, 0, 0, 0.05)'
                },
                ticks: {
                  callback: function(value) {
                    return value + ' kg';
                  },
                  font: {
                    size: 11
                  }
                }
              }
            },
            animation: {
              duration: 1000,
              easing: 'easeOutQuart'
            }
          }
        });
      }
      
      // 计算趋势线数据
      function calculateTrend(data) {
        // 简单线性回归计算趋势线
        const n = data.length;
        if (n < 2) return data;
        
        let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
        
        for (let i = 0; i < n; i++) {
          sumX += i;
          sumY += data[i];
          sumXY += i * data[i];
          sumX2 += i * i;
        }
        
        const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
        const intercept = (sumY - slope * sumX) / n;
        
        return data.map((_, i) => intercept + slope * i);
      }
      
      // 切换视图（周/月/年）
      function switchView(view) {
        // 移除所有活动状态
        document.querySelectorAll('.btn-toggle').forEach(btn => btn.classList.remove('active'));
        
        // 设置当前活动状态
        document.getElementById(`btn-${view}`).classList.add('active');
        currentView = view;
        
        // 更新数据
        switch (view) {
          case 'week':
            currentData = [...sampleData];
            recordsPerPage = 7;
            break;
          case 'month':
            currentData = generateSampleData(30);
            recordsPerPage = 10;
            break;
          case 'year':
            currentData = generateSampleData(365);
            recordsPerPage = 20;
            break;
        }
        
        // 更新表格每页显示数量
        document.getElementById('table-limit').value = recordsPerPage;
        
        // 重置分页
        currentPage = 1;
        
        // 更新图表和表格
        initChart();
        updateTable();
      }
      
      // 刷新数据
      function refreshData() {
        // 添加加载动画
        const refreshBtn = document.getElementById('refresh-btn');
        const originalContent = refreshBtn.innerHTML;
        refreshBtn.disabled = true;
        refreshBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 刷新中...';
        
        // 模拟数据加载延迟
        setTimeout(() => {
          // 根据当前视图重新生成数据
          switch (currentView) {
            case 'week':
              currentData = [...sampleData];
              break;
            case 'month':
              currentData = generateSampleData(30);
              break;
            case 'year':
              currentData = generateSampleData(365);
              break;
          }
          
          // 更新图表和表格
          initChart();
          updateTable();
          
          // 恢复按钮状态
          refreshBtn.disabled = false;
          refreshBtn.innerHTML = originalContent;
          
          // 添加成功提示
          showNotification('数据已更新', 'success');
        }, 800);
      }
      
      // 更新表格
      function updateTable() {
        const tableBody = document.getElementById('weight-table-body');
        const totalPages = Math.ceil(currentData.length / recordsPerPage);
        const startIdx = (currentPage - 1) * recordsPerPage;
        const endIdx = Math.min(startIdx + recordsPerPage, currentData.length);
        const paginatedData = currentData.slice(startIdx, endIdx);
        
        // 清空表格
        tableBody.innerHTML = '';
        
        // 更新分页信息
        document.getElementById('showing-start').textContent = startIdx + 1;
        document.getElementById('showing-end').textContent = endIdx;
        document.getElementById('total-entries').textContent = currentData.length;
        
        // 禁用/启用分页按钮
        document.getElementById('prev-page').disabled = currentPage === 1;
        document.getElementById('next-page').disabled = currentPage === totalPages;
        
        // 如果没有数据，显示空状态
        if (paginatedData.length === 0) {
          tableBody.innerHTML = `
            <tr>
              <td colspan="5" class="px-6 py-12 text-center text-gray-500">
                <div class="flex flex-col items-center">
                  <i class="fa fa-bar-chart text-4xl mb-4 text-gray-300"></i>
                  <p>暂无体重数据</p>
                  <button id="add-first-record" class="mt-3 px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-all duration-200">
                    添加第一条记录
                  </button>
                </div>
              </td>
            </tr>
          `;
          
          document.getElementById('add-first-record').addEventListener('click', openModal);
          return;
        }
        
        // 填充表格数据
        paginatedData.forEach((item, index) => {
          const nextItem = paginatedData[index + 1] || currentData[endIdx + index];
          const prevItem = paginatedData[index - 1] || currentData[startIdx + index - 1];
          
          // 计算与前一天的变化
          let change = '';
          let trendClass = '';
          let trendIcon = '';
          
          if (prevItem) {
            const diff = item.weight - prevItem.weight;
            
            if (diff > 0) {
              change = `+${diff.toFixed(1)}kg`;
              trendClass = 'text-danger';
              trendIcon = '<i class="fa fa-arrow-up"></i>';
            } else if (diff < 0) {
              change = `${diff.toFixed(1)}kg`;
              trendClass = 'text-secondary';
              trendIcon = '<i class="fa fa-arrow-down"></i>';
            } else {
              change = '持平';
              trendClass = 'text-gray-500';
              trendIcon = '<i class="fa fa-minus"></i>';
            }
          } else {
            change = '---';
            trendClass = 'text-gray-500';
            trendIcon = '<i class="fa fa-minus"></i>';
          }
          
          // 计算与目标的差距
          const targetDiff = item.weight - targetWeight;
          let targetStatus = '';
          
          if (targetDiff > 0) {
            targetStatus = `距离目标还有 ${targetDiff.toFixed(1)}kg`;
          } else if (targetDiff < 0) {
            targetStatus = `已超过目标 ${Math.abs(targetDiff).toFixed(1)}kg`;
          } else {
            targetStatus = '已达到目标！';
          }
          
          const row = document.createElement('tr');
          row.className = index % 2 === 0 ? 'bg-white' : 'bg-gray-50';
          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm font-medium text-gray-900">${formatDate(item.date)}</div>
              <div class="text-xs text-gray-500">${formatFullDate(item.date)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm font-medium text-gray-900">${item.weight} kg</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm ${trendClass}">${change}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm ${trendClass} flex items-center">
                ${trendIcon} ${targetStatus}
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              <button class="text-primary hover:text-primary/80 mr-3 edit-record" data-date="${item.date}">
                <i class="fa fa-pencil"></i> 编辑
              </button>
              <button class="text-danger hover:text-danger/80 delete-record" data-date="${item.date}">
                <i class="fa fa-trash"></i> 删除
              </button>
            </td>
          `;
          
          tableBody.appendChild(row);
        });
        
        // 添加编辑和删除事件监听器
        document.querySelectorAll('.edit-record').forEach(btn => {
          btn.addEventListener('click', function() {
            const date = this.getAttribute('data-date');
            const record = currentData.find(item => item.date === date);
            
            if (record) {
              document.getElementById('weight-value').value = record.weight;
              document.getElementById('weight-date').value = record.date;
              openModal();
            }
          });
        });
        
        document.querySelectorAll('.delete-record').forEach(btn => {
          btn.addEventListener('click', function() {
            const date = this.getAttribute('data-date');
            deleteWeightRecord(date);
          });
        });
      }
      
      // 更新每页显示数量
      function updateRecordsPerPage() {
        recordsPerPage = parseInt(document.getElementById('table-limit').value);
        currentPage = 1; // 重置到第一页
        updateTable();
      }
      
      // 上一页
      function prevPage() {
        if (currentPage > 1) {
          currentPage--;
          updateTable();
        }
      }
      
      // 下一页
      function nextPage() {
        const totalPages = Math.ceil(currentData.length / recordsPerPage);
        if (currentPage < totalPages) {
          currentPage++;
          updateTable();
        }
      }
      
      // 添加体重记录
      function addWeightRecord(e) {
        e.preventDefault();
        
        const weightInput = document.getElementById('weight-value');
        const dateInput = document.getElementById('weight-date');
        
        const weight = parseFloat(weightInput.value);
        const date = dateInput.value;
        
        // 检查是否已存在该日期的记录
        const existingIndex = currentData.findIndex(item => item.date === date);
        
        if (existingIndex !== -1) {
          // 更新现有记录
          currentData[existingIndex].weight = weight;
          showNotification('体重记录已更新', 'success');
        } else {
          // 添加新记录
          currentData.push({ date, weight });
          
          // 按日期排序
          currentData.sort((a, b) => new Date(a.date) - new Date(b.date));
          
          showNotification('体重记录已添加', 'success');
        }
        
        // 关闭模态框
        closeModal();
        
        // 重置表单
        weightInput.value = '';
        dateInput.value = new Date().toISOString().split('T')[0];
        
        // 更新图表和表格
        initChart();
        updateTable();
      }
      
      // 删除体重记录
      function deleteWeightRecord(date) {
        if (confirm('确定要删除这条体重记录吗？')) {
          const index = currentData.findIndex(item => item.date === date);
          
          if (index !== -1) {
            currentData.splice(index, 1);
            
            // 更新图表和表格
            initChart();
            updateTable();
            
            showNotification('体重记录已删除', 'warning');
          }
        }
      }
      
      // 打开模态框
      function openModal() {
        const modal = document.getElementById('add-weight-modal');
        const modalContent = document.getElementById('modal-content');
        
        modal.classList.remove('hidden');
        setTimeout(() => {
          modalContent.classList.remove('scale-95', 'opacity-0');
          modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
      }
      
      // 关闭模态框
      function closeModal() {
        const modal = document.getElementById('add-weight-modal');
        const modalContent = document.getElementById('modal-content');
        
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
          modal.classList.add('hidden');
        }, 300);
      }
      
      // 显示通知
      function showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        
        // 设置通知样式
        let bgColor, textColor, icon;
        
        switch (type) {
          case 'success':
            bgColor = 'bg-secondary';
            textColor = 'text-white';
            icon = 'fa-check-circle';
            break;
          case 'warning':
            bgColor = 'bg-warning';
            textColor = 'text-white';
            icon = 'fa-exclamation-circle';
            break;
          case 'error':
            bgColor = 'bg-danger';
            textColor = 'text-white';
            icon = 'fa-times-circle';
            break;
          default:
            bgColor = 'bg-primary';
            textColor = 'text-white';
            icon = 'fa-info-circle';
        }
        
        notification.className = `fixed top-4 right-4 ${bgColor} ${textColor} px-6 py-3 rounded-lg shadow-lg flex items-center z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0`;
        notification.innerHTML = `
          <i class="fa ${icon} mr-2"></i>
          <span>${message}</span>
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 显示通知
        setTimeout(() => {
          notification.classList.remove('translate-y-[-20px]', 'opacity-0');
        }, 10);
        
        // 自动关闭
        setTimeout(() => {
          notification.classList.add('translate-y-[-20px]', 'opacity-0');
          setTimeout(() => {
            document.body.removeChild(notification);
          }, 300);
        }, 3000);
      }
      
      // 格式化日期（简化版）
      function formatDate(dateString) {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        if (currentView === 'year') {
          return `${month}-${day}`;
        }
        
        return `${month}/${day}`;
      }
      
      // 格式化完整日期
      function formatFullDate(dateString) {
        const date = new Date(dateString);
        const options = { weekday: 'long' };
        return date.toLocaleDateString('zh-CN', options);
      }
    </script>
  </main>
</body>
</html> 